<template>
  <el-card shadow="never">
    <div class="el_form_box" style="height: auto">
      <el-form
        :key="props.searchForm.name"
        :model="formData"
        :label-width="props.searchForm.labelwidth"
        :size="props.searchForm.size"
        ref="elFormRef"
      >
        <el-row :gutter="20">
          <template
            v-for="item in props.searchForm.searchItems"
            :key="item.prop"
          >
            <el-col :span="6">
              <el-form-item :label="item.label" :prop="item.prop">
                <!-- input 类型 -->
                <template v-if="item.type == 'input'">
                  <el-input
                    clearable
                    v-model="formData[item.prop]"
                    :placeholder="item.placeholder ?? ''"
                  ></el-input>
                </template>
                <template v-if="item.type == 'cascader'">
                  <el-cascader
                    :options="twoLevelCity"
                    @change="changeValue"
                    v-model="formSelect"
                    :props="{
                      checkStrictly: true,
                      value: 'dictItemCode',
                      label: 'dictItemName',
                      children: 'childrenDictItemList'
                    }"
                    clearable
                  ></el-cascader>
                </template>
                <!-- input 类型 -->
                <!-- 
                    type="daterange"
                 -->
                <template v-if="item.type == 'data-picker'">
                  <el-date-picker
                    v-model="formData[item.prop]"
                    @change="pickerChange"
                    type="datetimerange"
                    range-separator="-"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :disabledDate="disabledDateFn"
                    :popper-options="{
                      modifiers: [
                        {
                          name: 'flip',
                          options: {
                            fallbackPlacements: ['bottom'],
                            allowedAutoPlacements: ['bottom']
                          }
                        }
                      ]
                    }"
                  />
                </template>
                <template v-if="item.type == 'select'">
                  <!-- 运营商 -->
                  <el-select
                    clearable
                  @change="selectChange"

                    v-if="item.prop == 'isp'"
                    v-model="formData[item.prop]"
                    :placeholder="item.placeholder ?? ''"
                  >
                    <el-option
                      :label="row.value"
                      :value="row.key"
                      :key="row.key"
                      v-for="row in ispSelectList"
                    />
                  </el-select>
                  <el-select
                    v-else
                    clearable
                  @change="selectChange"

                    v-model="formData[item.prop]"
                    :placeholder="item.placeholder ?? ''"
                  >
                    <el-option
                      :label="row.value"
                      :value="row.key"
                      :key="row.key"
                      v-for="row in item.options"
                    />
                  </el-select>
                </template>
                <!-- 支持搜索select -->
                <template v-if="item.type == 'filterSelect'">
                  <el-select
                  popper-class="no-wrap-popper"
                  @change="selectChange"
                    class="remote-select"
                    clearable
                    v-model="formData[item.prop]"
                    :placeholder="item.placeholder ?? ''"
                    filterable
                    :multiple="item.multiple ?? false"
                    :collapse-tags="item.collapseTags ?? false"
                  >
                    <el-option
                      :label="row.value"
                      :value="row.key"
                      :key="row.key"
                      v-for="row in item.options"
                    />
                  </el-select>
                </template>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
    </div>
    <div class="content-header">
      <div>
        <template v-for="item in searchForm.tableBtnItems" :key="item.name">
          <template v-if="item.type == 'slot'">
            <slot :name="item.slotName" v-bind="item"> </slot>
          </template>
          <template v-else>
            <el-button
              :type="item.btnType"
              @click="handBtn(item)"
              v-permission="`${item.code}`"
            >
              <div class="btn_box">
                <el-icon :size="14">
                  <component :is="item?.icon" v-if="item.icon"></component>
                </el-icon>
                <span>
                  {{ item.name }}
                </span>
              </div>
            </el-button>
          </template>
        </template>
      </div>
      <div class="flex-center">
        <template v-for="item in searchForm.formBtnItems" :key="item.name">
          <template v-if="item.type == 'slot'">
            <slot :name="item.slot" v-bind="item"> </slot>
          </template>
          <template v-else>
            <el-button
              :type="item.btnType"
              @click="handBtn(item)"
              v-permission="`${item.code}`"
            >
              <div class="btn_box">
                <el-icon :size="14">
                  <component :is="item?.icon" v-if="item.icon"></component>
                </el-icon>
                <span>
                  {{ item.name }}
                </span>
              </div>
            </el-button>
          </template>
        </template>
      </div>
    </div>
  </el-card>
  <downList ref="downListRef" @flash="flash"></downList>
</template>
<!-- **
 filterSelect - 支持搜索select
filterable 开启搜索
** -->

<script setup lang="ts">
import { ref, reactive, unref } from "vue"
import { storeToRefs } from "pinia"
import {
  exportExportProductApiPost,
  exportExportOrderApiPost
} from "@/api/fileDown"
import { ElMessage } from "element-plus"
const downList = defineAsyncComponent(() => import("@/components/downList.vue"))
const downListRef = ref<{ show: (title: string, row?: any) => void }>()
import { useColorStore } from "@/store/common"
const provinceStore = useColorStore()
const { twoLevelCity } = storeToRefs(provinceStore)
const elFormRef = ref()
interface Iprops {
  searchForm: {
    isProchildren?: number // 1要code+ name 2只code
    name?: string
    size?: string|number
    btnSize?: string
    tableBtnItems: any[]
    formBtnItems: any[]
    searchItems: any[]
    labelwidth: string
  }
}
// 白名单 省
const formSelect = ref([])
const formData = reactive<any>({})
let props = defineProps<Iprops>()
const emit = defineEmits(["my-btn"])

const disabledDateFn = (time: any) => {
  return time.getTime() > Date.now()
}
/*时间处理*/

/*select数据合集*/
const ispSelectList = ref([
  { key: "ChinaMobile", value: "中国移动", id: 1 },
  { key: "ChinaUnicom", value: "中国联通", id: 2 },
  { key: "ChinaTelecom", value: "中国电信", id: 3 },
  { key: "ChinaBroadnet", value: "中国广电", id: 4 },
  { key: "Other", value: "其他", id: 5 }
])

const saveFlash = ref<any>({
  page: null,
  code: null
})

/*级联数据处理*/
const changeValue = (val: any) => {
  if (val?.length == 1) {
    formData["whiteListProvince"] = val[0]
    // listSearch.condition.locationCityCode=null
  } else if (val?.length == 2) {
    formData["whiteListProvince"] = val[0]
    formData["whiteListCity"] = val[1]
    // listSearch.condition.locationCityCode=val[1]
  } else {
    // listSearch.condition.locationProvinceCode=null
    // listSearch.condition.locationCityCode=null
  }
}
/* 按钮处理*/
const handBtn = (item: any) => {
  emit("my-btn", item, filterEmptyValues(formData))
}
const selectChange = () => {
  emit("my-btn", {type:"search"}, filterEmptyValues(formData))
}
const pickerChange = () => {
  emit("my-btn", {type:"search"}, filterEmptyValues(formData))
}
/*下载板块*/
const btnDown = async (page: string, params: any) => {
  try {
    let res
    if (page == "product") {
      res = await exportExportProductApiPost(params)
    } else if (page == "inventoryPackageOrder") {
      res = await exportExportOrderApiPost(params)
    }
    if (res && res.code == 20000) {
      ElMessage({
        type: "success",
        message: "下载成功 请查看下载列表 未出现下载数据 可等待在刷新下载列表！"
      })
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: "下载失败 请稍后再试！"
    })
  }
}
const btnDownList = async (page: string, code: any) => {
  // 发送请求 传递数据
  /*
CHANNEL( "channel", "渠道信息"),
PRODUCT( "product", "产品信息"),
INVENTORY_PACKAGE_ORDER( "inventoryPackageOrder", "存量包订单信息")
*/
  saveFlash.value.page = page
  saveFlash.value.code = code
  downListRef.value?.show(page, code)
}
const flash = () => {
  downListRef.value?.show(saveFlash.value.page, saveFlash.value.code)
}
/*处理搜索数据*/
const filterEmptyValues = (obj: any) => {
  // 删除数据类
  if (formData.formSelect) delete formData.formSelect
  let result: any = {}
  for (let key in obj) {
    if (Array.isArray(obj[key])) {
      if (obj[key].length > 0) {
        result[key] = obj[key]
      }
    } else {
      if (obj[key] !== "" && obj[key] !== null) {
        result[key] = obj[key]
      }
    }
  }
  return unref(result) ? unref(result) : result
}
const resetForm = () => {
  for (const item in formData) {
    formData[item] = ""
  }
  elFormRef.value.resetFields()
  formSelect.value = []
}

defineExpose({
  resetForm,
  formData,
  btnDown,
  btnDownList
})
</script>
<style lang="scss">
.el-card__body {
  padding: 12px 20px !important;
}

.el-cascader {
  width: 100%;
}



</style>

<style lang="scss" scope>
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-radius: 6px;

  .btn_box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
// 多选搜索溢出
.el-select__input-wrapper{
overflow: hidden;
}
.el_form_box {
  box-sizing: border-box;
  padding: 6px 20px;

  .border {
    width: 100%;
    height: 2px;
    border-bottom: 1px solid #ebeef5;
  }
}

.el-input__wrapper,
.el-select__wrapper {
  background-color: #f7f8fa !important;
}

</style>
